package com.zzy.utils;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.elasticsearch.client.*;

import java.io.IOException;


import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;

/**
 * 创建索引
 */
public class CreateIndex {


    public static void main(String[] args) {
        testCreateIndex();
    }

    public static void testCreateIndex() {
        HttpHost httpHost = new HttpHost("192.168.15.128", 9200, "http");
        RestClientBuilder rb = RestClient.builder(httpHost);

        rb.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder builder) {
                return builder.setConnectTimeout(20000)// 链接超时  毫秒
                        .setSocketTimeout(20000) // 请求超时  毫秒
                        ;
            }
        });

        RestHighLevelClient client = new RestHighLevelClient(rb);

        try {
            System.out.println("打开了 elasticsearch 链接。");


            System.out.println("开始创建索引：zzyuser");
            CreateIndexRequest request =   new CreateIndexRequest("zzyuser");


            CreateIndexResponse createIndexResponse = client.indices().create( request, RequestOptions.DEFAULT);

            boolean acknowledged = createIndexResponse.isAcknowledged();//响应状态
            System.out.println("返回结果，响应状态：");
            System.out.println(acknowledged);

            client.close();//关闭链接
            System.out.println("关闭了 elasticsearch 链接。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
